<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>智能家居设备状态</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet" />
  <script src="https://unpkg.com/lucide@latest"></script>
  <style>
    body {
      background: #f3f4f6;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    h1 {
      font-weight: 900;
      font-size: 2.75rem;
      color: #111827;
      margin-bottom: 3rem;
      text-shadow: 0 1px 2px rgba(0,0,0,0.05);
    }
    .card {
      background-color: white;
      border-radius: 1.5rem;
      padding: 2rem 2.5rem;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
      border: 1px solid transparent;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .card:hover {
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
      transform: translateY(-4px);
    }
    .device-on {
      border-color: #34d399;
      box-shadow: 0 0 12px #34d399aa;
    }
    .device-off {
      border-color: #e5e7eb;
      box-shadow: none;
    }
    .lightbulb-on {
      color: #facc15;
      filter: drop-shadow(0 0 10px #facc15);
      animation: glowPulse 3s ease-in-out infinite;
      opacity: 1;
    }
    .lightbulb-off {
      color: #9ca3af;
      opacity: 0.35;
      transition: opacity 0.5s ease;
    }
    @keyframes glowPulse {
      0%, 100% { filter: drop-shadow(0 0 10px #fbbf24); opacity: 1; }
      50% { filter: drop-shadow(0 0 20px #fbbf24); opacity: 0.85; }
    }
    .ac-cold {
      background: linear-gradient(135deg, #bae6fd, #0c4a6e);
      color: #ecfeff;
      box-shadow: 0 0 18px #0284c7aa;
    }
    .ac-hot {
      background: linear-gradient(135deg, #fecaca, #991b1b);
      color: #fee2e2;
      box-shadow: 0 0 18px #dc2626aa;
    }
    .ac-dry {
      background: linear-gradient(135deg, #e0e7ff, #3730a3);
      color: #e0e7ff;
      box-shadow: 0 0 18px #4338caaa;
    }
    .ac-auto {
      background: linear-gradient(135deg, #bef264, #365314);
      color: #f0fdf4;
      box-shadow: 0 0 18px #4d7c0faa;
    }
    .param-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0.6rem;
      font-size: 1rem;
      font-weight: 500;
      color: #374151;
    }
    .param-label {
      color: #6b7280;
      font-weight: 400;
    }
    .btn {
      cursor: pointer;
      padding: 0.6rem 1.5rem;
      border-radius: 9999px;
      font-weight: 700;
      border: none;
      user-select: none;
      box-shadow: 0 5px 10px rgba(0,0,0,0.08);
      transition: transform 0.25s ease, box-shadow 0.25s ease, background-color 0.3s ease;
      font-size: 1.05rem;
    }
    .btn-primary {
      background-color: #3b82f6;
      color: white;
    }
    .btn-primary:hover {
      background-color: #2563eb;
      box-shadow: 0 10px 15px rgba(37, 99, 235, 0.4);
      transform: scale(1.1);
    }
    .btn-secondary {
      background-color: #9ca3af;
      color: white;
    }
    .btn-secondary:hover {
      background-color: #6b7280;
      box-shadow: 0 10px 15px rgba(107, 114, 128, 0.4);
      transform: scale(1.1);
    }
    .buttons-wrapper {
      margin-top: 1.8rem;
      display: flex;
      gap: 1rem;
      justify-content: center;
    }
    .icon-title {
      display: flex;
      align-items: center;
      gap: 1rem;
      margin-bottom: 1.6rem;
      font-weight: 700;
      font-size: 1.5rem;
      color: #1f2937;
      user-select: none;
    }
    .icon-title i {
      stroke-width: 2.5;
    }
  </style>
</head>
<body>
  <h1 class="text-center">智能家居设备状态</h1>
  <div id="device-container" class="grid grid-cols-1 md:grid-cols-2 gap-12 max-w-5xl mx-auto px-4"></div>

  <script>
  const container = document.getElementById('device-container');

  let devices = [
    {
      product_id: { value: "mD97Vya1hi" },
      device_name: { value: "d1" },
      device_type: "LED Light",
      params: {
        properties: {
          led: { description: "LED开关状态" }
        }
      },
      status: { led: false }
    },
    {
      product_id: { value: "aX23Jrf5xy" },
      device_name: { value: "空调" },
      device_type: "Air Conditioner",
      params: {
        properties: {
          power: { description: "开关状态" },
          temperature: { description: "设定温度" },
          fan_speed: { description: "风速级别" },
          mode: { description: "空调模式" }
        }
      },
      status: { power: false, temperature: 24, fan_speed: 3, mode: "冷" }
    }
  ];

  function getDeviceIcon(type, isOn) {
    switch(type) {
      case 'LED Light': return isOn ? 'lightbulb' : 'lightbulb-off';
      case 'Air Conditioner': return 'snowflake';
      default: return 'cpu';
    }
  }

  function getAcClass(power, mode) {
    if (!power) return '';
    switch(mode) {
      case '冷': return 'ac-cold';
      case '热': return 'ac-hot';
      case '除湿': return 'ac-dry';
      case '自动': return 'ac-auto';
      default: return '';
    }
  }

  function renderDevice(device) {
    const key = device.product_id.value;
    const isLight = device.device_type === 'LED Light';
    const isAc = device.device_type === 'Air Conditioner';
    const status = device.status;

    const powerKey = isLight ? 'led' : 'power';
    const isOn = status[powerKey] === true;

    let cardClass = 'card ' + (isOn ? 'device-on' : 'device-off');
    if (isAc) cardClass += ' ' + getAcClass(status.power, status.mode);

    let iconName = getDeviceIcon(device.device_type, isOn);

    let iconClass = '';
    if (isLight) iconClass = isOn ? 'lightbulb-on' : 'lightbulb-off';

    let paramsHtml = '';
    for (const [key, val] of Object.entries(device.params.properties)) {
      let dispVal = status[key];
      if (dispVal === undefined || dispVal === null) dispVal = '-';
      paramsHtml += `
        <div class="param-row">
          <span class="param-label">${val.description}</span>
          <span>${dispVal}</span>
        </div>
      `;
    }

    let controlsHtml = '';
    if (isLight) {
      controlsHtml = `
        <button class="btn btn-primary" onclick="toggleLight('${key}')">${isOn ? '关闭灯泡' : '打开灯泡'}</button>
      `;
    } else if (isAc) {
      controlsHtml = `
        <div class="buttons-wrapper">
          <button class="btn btn-primary" onclick="toggleAcPower('${key}')">${isOn ? '关闭空调' : '打开空调'}</button>
          <button class="btn btn-secondary" onclick="decreaseTemperature('${key}')">温度 -</button>
          <button class="btn btn-secondary" onclick="increaseTemperature('${key}')">温度 +</button>
          <button class="btn btn-secondary" onclick="changeAcMode('${key}')">模式: ${status.mode}</button>
        </div>
      `;
    }

    const cardHtml = `
      <div id="${key}" class="${cardClass}">
        <div class="icon-title">
          <i data-lucide="${iconName}" class="${iconClass} w-10 h-10"></i>
          <div>${device.device_name.value}</div>
        </div>
        <div>
          ${paramsHtml}
        </div>
        ${controlsHtml}
      </div>
    `;

    const existing = document.getElementById(key);
    if (existing) {
      existing.outerHTML = cardHtml;
    } else {
      container.insertAdjacentHTML('beforeend', cardHtml);
    }
    lucide.createIcons();
  }

  // 找设备：优先用 product_id.value（匹配后端device_id），找不到用 device_name.value（匹配后端device_name）
  function findDeviceByBackendCall(deviceCall) {
    let device = devices.find(d => d.product_id.value === deviceCall.device_id);
    if (device) return device;
    device = devices.find(d => d.device_name.value === deviceCall.device_name);
    if (device) return device;
    return null;
  }

  // 根据后端config更新设备状态
  function updateDeviceStatusFromConfig(device, config) {
    if (!device || !config) return;

    if (device.device_type === 'LED Light' && config.led !== undefined) {
      device.status.led = config.led;
    }
    else if (device.device_type === 'Air Conditioner') {
      // 可能多个字段一起更新
      if (config.power !== undefined) device.status.power = config.power;
      if (config.temperature !== undefined) device.status.temperature = config.temperature;
      if (config.fan_speed !== undefined) device.status.fan_speed = config.fan_speed;
      if (config.mode !== undefined) device.status.mode = config.mode;
    }
    // 如果有其他设备类型，依此类推添加...
  }

  // 交互操作函数保持不变，调用renderDevice刷新即可

  function toggleLight(id) {
    const dev = devices.find(d => d.product_id.value === id);
    if (!dev) return;
    dev.status.led = !dev.status.led;
    renderDevice(dev);
  }

  function toggleAcPower(id) {
    const dev = devices.find(d => d.product_id.value === id);
    if (!dev) return;
    dev.status.power = !dev.status.power;
    renderDevice(dev);
  }

  function increaseTemperature(id) {
    const dev = devices.find(d => d.product_id.value === id);
    if (!dev) return;
    if (dev.status.temperature < 30) {
      dev.status.temperature++;
      renderDevice(dev);
    }
  }

  function decreaseTemperature(id) {
    const dev = devices.find(d => d.product_id.value === id);
    if (!dev) return;
    if (dev.status.temperature > 16) {
      dev.status.temperature--;
      renderDevice(dev);
    }
  }

  function changeAcMode(id) {
    const dev = devices.find(d => d.product_id.value === id);
    if (!dev) return;
    const modes = ['冷', '热', '除湿', '自动'];
    let idx = modes.indexOf(dev.status.mode);
    idx = (idx + 1) % modes.length;
    dev.status.mode = modes[idx];
    renderDevice(dev);
  }

  devices.forEach(d => renderDevice(d));

  // —— 新增：通过 SSE 实时更新设备状态 —— //

  const eventSource = new EventSource('/api/device-status-stream'); // 替换为你后端 SSE 地址

  eventSource.onmessage = async function (event) {
    const msg = JSON.parse(event.data);
    const callId = msg.call_id;
    const deviceCalls = msg.device_calls;
    if (msg.device_calls && Array.isArray(msg.device_calls)) {
      msg.device_calls.forEach(dc => {
        const device = findDeviceByBackendCall(dc);
        if (!device) {
          console.warn("[SSE] 未找到匹配的设备:", dc);
          return;
        }

        updateDeviceStatusFromConfig(device, dc.config);
        renderDevice(device);
      });
      // 构造响应数据：带 success + 原始控制数据（data）
      const resultPayload = {
        call_id: callId,
        result: {
          success: true,
          data: deviceCalls
        }
      };

      // 发送 POST 返回到后端（API: /api/device-call-result）
      await fetch("/api/device-call-result", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(resultPayload)
      });

      console.log("[SSE] 已发送执行结果:", resultPayload);
    }
  };

</script>


</body>
</html>
